package com.yuou.controller;


import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yuou.annotation.SystemLog;
import com.yuou.common.base.BlogerBaseController;
import com.yuou.model.Bloger;
import com.yuou.model.BlogerRole;
import com.yuou.model.Message;
import com.yuou.service.BlogerRoleService;
import com.yuou.service.BlogerService;
import com.yuou.service.MessageService;
import com.yuou.shiro.ShiroDbRealm;
import com.yuou.util.CipherUtil;
import com.yuou.util.ConstantUtil;
import com.yuou.util.SendEmailUtil;
import com.yuou.util.UserIpUtil;



@Controller
public class BlogerController extends BlogerBaseController {
	@Resource(name = "blogerServiceImpl")
	private BlogerService blogerService;
	
	@Resource(name = "blogerRoleServiceImpl")
	private BlogerRoleService blogerRoleService;
	
	@Resource(name = "messageServiceImpl")
	private MessageService messageService;
	
	 /** 
     * 初始登陆界面 
     * @param request 
     * @return 
     */  
    @RequestMapping("/login")  
    public String tologin(HttpServletRequest request, HttpServletResponse response, Model model){  
    	
    	return "login";  
    }  
    @RequestMapping("/sendEmail") 
    @ResponseBody
    public Map<String,Object> tofindPwd(HttpServletRequest request, HttpServletResponse response, Bloger bloger){ 
    	Map<String,Object> mapResult = new HashMap<String,Object>();
    	Bloger fbloger = blogerService.getUserByLoginName(bloger.getUsername());
    	if(fbloger!=null) {
    		if(fbloger.getEmail().equals(bloger.getEmail())) {
    			mapResult.put("id", fbloger.getId());
    			int code = (int) ((Math.random()*9+1)*10000000);
    			String ccode=DigestUtils.md5Hex(DigestUtils.md5Hex(bloger.getUsername()+code));
    			try {
					SendEmailUtil.sendHtmlEmail(fbloger.getEmail(), code);
    				System.out.println(code);
					mapResult.put("result", "验证码邮件已经发送到邮箱,请到邮箱查看~");
					mapResult.put("code", ccode);
					mapResult.put("status", "200");
					System.out.println(ccode);
				} catch (Exception e) {
					mapResult.put("result", "邮件发送失败,请联系管理员~");
					mapResult.put("status", "500");
				}
    			
    		}else {
    			mapResult.put("result", "请检查用户名和邮箱是否正确！！");
    			mapResult.put("status", "404");
    		}
    	}else {
    		mapResult.put("result", "请检查用户名和邮箱是否正确！！");
    		mapResult.put("status", "404");
    	}
    	return mapResult;  
    } 
    
    @RequestMapping("/pwdByEmail") 
    @ResponseBody
    public Map<String,Object> pwdByEmail(HttpServletRequest request, HttpServletResponse response, Bloger bloger){ 
    	Map<String,Object> mapResult = new HashMap<String,Object>();
    	String password = CipherUtil.generatePassword(CipherUtil.generatePassword(bloger.getPassword()+bloger.getUsername()));
    	int count= blogerService.updatePassword(bloger.getId(), password);
    	if(count>0) {
    		mapResult.put("status", "200");
    	}else {
    		mapResult.put("status", "500");
    	}
    	return mapResult;  
    } 
      
    /** 
     * 验证用户名和密码 
     * @param request 
     * @return 
     */  
    @RequestMapping(value="/checkLogin/{username}",method = RequestMethod.POST)
    @SystemLog(description = ConstantUtil.LOGIN_IN,userType=ConstantUtil.USERTYPE_ADMIN) 
    public String login(@PathVariable(value = "username") String username,String password,Model model,HttpServletRequest request) {
    	String result = "";
    	try {
            Bloger bloger = blogerService.getUserByLoginName(username);
        	String tpassword = password;
        	BlogerRole blogerRole=null;
        	if(bloger!=null) {
        		blogerRole = blogerRoleService.selectByblogerId(bloger.getId());
        	}
        	model.addAttribute("blogerRole",blogerRole);
             
            //取得 密码，并用MD5加密  
            password = CipherUtil.generatePassword(CipherUtil.generatePassword(password+username));
            //System.out.println("password================"+password);
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);  
            Subject currentUser = SecurityUtils.getSubject(); 
            try {  
                //if (!currentUser.isAuthenticated()){//使用shiro来验证 
                    token.setRememberMe(false);  //记住密码
                    currentUser.login(token);//验证角色和权限  
                    //System.out.println("走了验证===========shiro");
                //}
                result = "admin/index";//验证成功  
            }  catch(LockedAccountException le) {
            	result = "login";//验证失败  
                model.addAttribute("message", "账号被冻结,请联系管理员！");
                model.addAttribute("username", username);
                model.addAttribute("password", tpassword);
            }  catch (AuthenticationException ae) {  
                result = "login";//验证失败  
                model.addAttribute("message", "用户名或密码错误");
                model.addAttribute("username", username);
                model.addAttribute("password", tpassword);
            } 
        }catch(Exception e){
            e.printStackTrace();
        } 
    	
        return result;  
    }  
    
    /** 
     * 退出 
     * @return 
     */  
    @RequestMapping(value = "/admin/logout/{username}")  
    @SystemLog(description = ConstantUtil.LOGIN_OUT,userType=ConstantUtil.USERTYPE_ADMIN) 
    public String logout(@PathVariable(value = "username") String username,ShiroDbRealm shiro) {    
        Subject currentUser = SecurityUtils.getSubject();
        String result = "login";    
        currentUser.logout();    
        return result;    
    }
    @RequestMapping(value="/checkLogin/{username}",method = RequestMethod.GET)  
    @SystemLog(description = ConstantUtil.LOGIN_OUT,userType=ConstantUtil.USERTYPE_ADMIN) 
    public String logout(@PathVariable(value = "username") String username) {    
        String result = "login";    
        return result;    
    } 
    
    /**
	  * 发送消息功能
	  * @param blog
	  * @return
	  * @throws Exception
	  */
	 @RequestMapping(value = "/addMessage",method = RequestMethod.POST)
	 @SystemLog(description = ConstantUtil.MESSAGE_ADD,userType=ConstantUtil.USERTYPE_USER) 
	 public String addMessage(Model model,Message message,ServletRequest srequest) throws Exception{
		 HttpServletRequest request = (HttpServletRequest) srequest;
		 String ip=UserIpUtil.getIp(request);
		 message.setIp(ip);
		 message.setCreateDate(new Date());
		 String result="error/blackIp";
		 if(messageService.insertMessage(message)!=0){
			 model.addAttribute("result", "提交成功");
		 }else{
			 model.addAttribute("result", "提交失败");
		 }
		 return result;
	 }
   }
